const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");
const expressjWT = require("express-jwt");
const secrectKey = "itemheima-gangshao2016-^_^";
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const session = require("express-session");
app.use(
  session({
    secret: "itemheima-gangshao2016",
    resave: false,
    saveUninitialized: true,
  })
);
app.use(
  expressjWT
    .expressjwt({ secret: secrectKey, algorithms: ["HS256"] })
    // .unless({ path: [/^\/api\//] })
    .unless({ path: ["/login"] })
);
// 登录接口
app.post("/login", (req, res) => {
  console.log(req, "req-------------");
  if (req.body.username == "admin" || req.body.password == "000000") {
    return res.send({ status: 1, msg: "登录失败" });
  }
  req.session.user = req.body;
  req.session.islogin = true;
  const token = jwt.sign({ username: req.body.username }, secrectKey, {
    expiresIn: "1s",
  });

  res.send({ status: 0, msg: "登录成功", data: req.session, token });
});

// 从session中获取用户信息
app.get("/userName", (req, res) => {
  console.log(res, "req-------------");
  res.send({ status: 0, msg: "success" });
  /*  if (!req.body.islogin) {
    return res.send({ status: 1, msg: "fail" });
  }

  res.send({ status: 0, msg: "success", req: req }); */
});
app.use((err, req, res, next) => {
  console.log("【Error】:" + err.message);
  console.log(err.name, "UnauthorizedError?.name===========");
  if ((err.name = "UnauthorizedError")) {
    return res.send({
      satus: 401,
      msg: "token失效，请重新登录",
    });
  }
  res.send({
    satus: 500,
    msg: "位置错误",
  });
});
app.listen(80, () => {
  console.log("Server is running on port 80");
});
